package org.boticelli.auth;

import java.util.Arrays;
import java.util.List;

import javax.persistence.Transient;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.UserDetails;
import org.boticelli.model.User;

public class BoticelliUserDetails
        implements UserDetails
{
    private static final long serialVersionUID = 5433676405271930067L;

    private String name;

    private String password;

    private GrantedAuthority[] authorities;

    private boolean locked;

    public BoticelliUserDetails(User u)
    {
        this(u.getName(), u.getPassword(), u.getRolesAsList(), u.isLocked());
    }

    public BoticelliUserDetails(String name, String password, List<String> roles, boolean locked)
    {
        this.name = name;
        this.password = password;
        this.locked = locked;

        authorities = new GrantedAuthority[roles.size()];
        int cnt = 0;
        for (String role : roles)
        {
            authorities[cnt++] = new GrantedAuthorityImpl(role);
        }
    }

    public GrantedAuthority[] getAuthorities()
    {
        return authorities;
    }

    public String getPassword()
    {
        return password;
    }

    public String getUsername()
    {
        return name;
    }

    public boolean isAccountNonExpired()
    {
        return true;
    }

    public boolean isAccountNonLocked()
    {
        return !locked;
    }

    public boolean isCredentialsNonExpired()
    {
        return true;
    }

    public boolean isEnabled()
    {
        return true;
    }

    @Transient
    public String getUniqueUserId()
    {
        return String.valueOf("user-"+name.hashCode());
    }

    @Override
    public String toString()
    {
        return super.toString() + ": name = " + name + ", password = " + password
                + ", authorities = " + Arrays.asList(authorities);
    }
}
